﻿using AutoMapper;
using SalesSys.BLL;
using SalesSys.Comm.BLL;
using SalesSys.DAL.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using hlib.IO;
using System.IO;
using System.Text;
using System.Transactions;
using Newtonsoft.Json;


namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 客户管理
    /// </summary>
    [RoutePrefix("api/Customer")]
    public class CustomerController : BaseApiController
    {
        CustomerBLL entityBLL = BLL.BllFactory.GetBll<CustomerBLL>();
        EmployeeBLL employeeBLL = BLL.BllFactory.GetBll<EmployeeBLL>();
        DistrictBLL districtBLL = BLL.BllFactory.GetBll<DistrictBLL>();
        AccountBLL accountBLL = BLL.BllFactory.GetBll<AccountBLL>();
        private CustomerContactBLL customerContactBLL = BLL.BllFactory.GetBll<CustomerContactBLL>();
        private AccountantContactBLL austomerContactBLL = BLL.BllFactory.GetBll<AccountantContactBLL>();
        private CustomerOperateRecordBLL customerOperateRecordBLL = BLL.BllFactory.GetBll<CustomerOperateRecordBLL>();
        private CustomerBalanceBLL customerBalanceBLL = BLL.BllFactory.GetBll<CustomerBalanceBLL>();

        /// <summary>
        /// 客户列表
        /// </summary>
        /// <param name="like">模糊查询</param>
        /// <param name="state">状态</param>
        /// <param name="isDel">是否删除</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>客户列表</returns>
        [Route("List")]
        public ViewDtos<Customer> Get(string like = null, DateTime? startTime = null, DateTime? endTime = null, ApprovalState? state = null, bool? isDel = false, int page = 1, int rows = 10)
        {
            var data = entityBLL.Select(like, startTime, endTime, state, GetRequestQuery() as QueryInfo, isDel);
            var dto = ViewDto.CreateList(data.Value);
            dto.Total = data.Key;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }

        /// <summary>
        /// 导出客户
        /// </summary>
        /// <returns></returns>
        [Route("ExpCustomer")]
        [HttpGet]
        public HttpResponseMessage ExpCustomer()
        {
            var data = entityBLL.Select(null, null, null, null, new QueryInfo() { Page = 1, Rows = 19999 });
            HttpResponseMessage msg = null;
            var expData =
                data.Value.Select(
                    p =>
                        new string[]
                        {
                            p.Id.ToString(), p.Name, p.ShortName, p.ApprovalState.GetDescription(), "\t"+p.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                            p.Accountant, "\t"+p.AccountantPhone, p.Contacts, p.ContactPosition, "\t"+p.ContactPhone,
                            "\t"+p.CreditID, "\t"+p.IDCode, p.Remarks, p.IsPersonal.ToString()=="false"?"否":"是", p.IsDelete.ToString()=="false"?"否":"是"
                        });

            var nameArray = new string[] { "id", "名称", "短名称", "审批状态", "创建时间", "财务", "财务电话", "联系人", "职务", "电话", "信用代码", "身份证", "备注", "个人", "已删除" };
            msg = CsvExp("客户数据.csv", expData, nameArray);

            return msg;
        }


        /// <summary>
        /// 客户详情
        /// </summary>
        /// <param name="id">客户编号</param>
        /// <returns>客户实体</returns>
        [Route("Detail")]
        public Customer GetDetail(Guid id)
        {
            return entityBLL.Details(id);
        }

      /// <summary>
      /// 获取客户户头列表
      /// </summary>
      /// <param name="id">客户Id</param>
        /// <returns>客户实体</returns>
        public Customer GetAccountsList(Guid id)
        { 
            //获取客户信息
            Customer cusInfo = entityBLL.Details(id);
            //获取客户户头信息
            if (cusInfo!=null&&cusInfo.Accounts!=null&&cusInfo.Accounts.Count>0)
            {
                foreach (var item in cusInfo.Accounts)
                {
                    //通过客户和客户经理获取当前户头的余额
                  item.Amount= customerBalanceBLL.GetAccountAmount(id, ClientHelper.ClientInfo.Id, item.Id);
                }
            }
            return cusInfo;
        }
        /// <summary>
        /// 客户报备
        /// </summary>
        /// <param name="customer">客户实体</param>
        /// <returns>客户编号</returns>
        public Guid Post(Customer customer)
        {
            using (var tran = new TransactionScope())
            {
                var nowCust = entityBLL.ExistByName(customer);
                if (nowCust != null && nowCust.IsDelete == false && nowCust.ApprovalState != ApprovalState.Disagree)
                {
                    throw new ApiArgException("客户名称已报备，如未找到，可能是正在处理中，可稍后联系客服确认");
                }
                customer.CreateTime = DateTime.Now;
                if (customer.District != null)
                {
                    customer.District = districtBLL.Details(customer.District.Id);
                }

                customer.ApprovalState = ApprovalState.Agree;
                customer.CreditScore = 80;
                if (customer.ClientManager != null)
                {
                    customer.ClientManager = employeeBLL.Details(customer.ClientManager.Id);
                }
                entityBLL.AddCashAccountIfNon(customer);
                entityBLL.Create(customer);
                //添加普通客户联系人
                List<CustomerContact> customerContacts = customer.CustomerContacts.ToList();
                if (customerContacts.Count > 0)
                {
                    foreach (var item in customerContacts)
                    {
                        item.CustomerId = customer.Id;
                        customerContactBLL.Create(item);
                    }
                }
                //添加财务联系人
                List<AccountantContact> accountantContacts = customer.AccountantContacts.ToList();
                if (accountantContacts.Count > 0)
                {
                    foreach (var item in accountantContacts)
                    {
                        item.CustomerId = customer.Id;
                        austomerContactBLL.Create(item);
                    }
                }
                //添加客户操作记录表
                CustomerOperateRecord operateRecord = new CustomerOperateRecord();
                operateRecord.OperatorAction = "Create";
                operateRecord.CustomerId = customer.Id;
                operateRecord.BeforeContent = "";
                customer.District = new District();
                customer.District.Children = null;
                customer.District.Parent = null;
                operateRecord.AfterContent = SalesSys.Comm.Utility.SimpleJson.Serializer(customer);
                operateRecord.OperatorTime = DateTime.Now;
                operateRecord.OperatorId = ClientHelper.ClientInfo.Id;
                operateRecord.Id = Guid.NewGuid();
                customerOperateRecordBLL.Create(operateRecord);
                //添加客户余额表
                CustomerBalance customerBalance = new CustomerBalance();
                customerBalance.CustomerId = customer.Id;
                customerBalance.Balance = 0;
                customerBalance.EmployeeId = customer.ClientManager.Id;
                customerBalance.Id = Guid.NewGuid();
                customerBalanceBLL.Create(customerBalance);
                tran.Complete();
                return customer.Id;

            }
        }

        /// <summary>
        /// 修改客户
        /// </summary>
        /// <param name="customer">客户实体</param>
        public void Put(Customer customer)
        {
            using (var tran = new TransactionScope())
            {
                CustomerOperateRecord operateRecord = new CustomerOperateRecord();
                var nowCust = entityBLL.ExistByName(customer);
                if (nowCust != null && nowCust.Id != customer.Id && nowCust.IsDelete == false && nowCust.ApprovalState != ApprovalState.Disagree)
                {
                    throw new ApiArgException("客户名称已报备");
                }
                var old = entityBLL.Details(customer.Id);
                operateRecord.BeforeContent = SalesSys.Comm.Utility.SimpleJson.Serializer(old);
                if (customer.District != null)
                    old.District = districtBLL.Details(customer.District.Id);
                if (customer.ClientManager != null)
                {
                    old.ClientManager = employeeBLL.Details(customer.ClientManager.Id);
                }
                CMapper.Map(customer, old);

                //普通联系人处理(先做删除，再做添加)
                var oldCustomerContacts = old.CustomerContacts.ToList();
                if (oldCustomerContacts.Count > 0)
                {
                    var oldCount = oldCustomerContacts.Count;
                    for (int i = 0; i < oldCount; i++)
                    {
                        var item = oldCustomerContacts[i];
                        customerContactBLL.Delete(item.Id);
                    }
                }
                List<CustomerContact> customerContacts = customer.CustomerContacts.ToList();
                if (customerContacts.Count > 0)
                {
                    foreach (var item in customerContacts)
                    {
                        item.CustomerId = customer.Id;
                        customerContactBLL.Create(item);
                    }
                }
                //财务联系人处理
                var oldAccountantContacts = old.AccountantContacts.ToList();
                if (oldAccountantContacts.Count > 0)
                {
                    var oldCount = oldAccountantContacts.Count;
                    for (int i = 0; i < oldCount; i++)
                    {
                        var item = oldAccountantContacts[i];
                        austomerContactBLL.Delete(item.Id);
                    }
                }

                List<AccountantContact> accountantContacts = customer.AccountantContacts.ToList();
                if (accountantContacts.Count > 0)
                {
                    foreach (var item in accountantContacts)
                    {
                        item.CustomerId = customer.Id;
                        austomerContactBLL.Create(item);
                    }
                }
                //添加客户操作记录表

                operateRecord.OperatorAction = "Edit";
                operateRecord.CustomerId = customer.Id;
                customer.District = new District();
                customer.District.Children = null;
                customer.District.Parent = null;
                operateRecord.AfterContent = SalesSys.Comm.Utility.SimpleJson.Serializer(customer);
                operateRecord.OperatorTime = DateTime.Now;
                operateRecord.OperatorId = ClientHelper.ClientInfo.Id;
                operateRecord.Id = Guid.NewGuid();
                customerOperateRecordBLL.Create(operateRecord);
                if (old.ApprovalState == ApprovalState.Disagree)
                    old.ApprovalState = ApprovalState.Pending;

                entityBLL.Edit(old);

                //先行判断该客户在余额表中是否存在
                if (!customerBalanceBLL.IsExistAccount(customer.Id, customer.ClientManager.Id))
                {
                    CustomerBalance customerBalance = new CustomerBalance();
                    customerBalance.CustomerId = customer.Id;
                    customerBalance.Balance = 0;
                    customerBalance.EmployeeId = customer.ClientManager.Id;
                    customerBalance.Id = Guid.NewGuid();
                    customerBalanceBLL.Create(customerBalance);
                }
                tran.Complete();
            }
        }

        /// <summary>
        /// 客户审核
        /// </summary>
        /// <param name="customerId">客户编号</param>
        /// <param name="isPass">审核结果</param>
        [Route("Confirm")]
        public void PutConfirm(Guid customerId, bool isPass)
        {
            var entity = entityBLL.Details(customerId);
            if (entity == null || entity.ApprovalState == ApprovalState.Agree || entity.ApprovalState == ApprovalState.Disagree)
            {
                throw new ApiArgException("客户无法找到或客户状态错误");
            }
            entity.ApprovalState = isPass ? ApprovalState.Agree : ApprovalState.Disagree;
            if (entity.ApprovalState == ApprovalState.Agree)
                entityBLL.AddCashAccountIfNon(entity);
            entity.AddRecord("被审核，审核状态为：" + entity.ApprovalState.GetDescription());
            entityBLL.Edit(entity);
            if (!isPass)
            {
                SendMsg(entity);
            }
        }
        
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="cst">客户实体</param>
        private void SendMsg(Customer cst)
        {
            if (cst.ClientManager == null)
            {
                return;
            }
            var nb = new NoticeInfoBLL();
            var str = string.Format("{0:M/d HH:mm} [客户报备驳回]{1}", DateTime.Now, cst.Name);
            nb.SendMsg(str, cst.ClientManager.Id, null);
        }

        /// <summary>
        /// 客户逻辑删除
        /// </summary>
        /// <param name="id">客户编号</param>
        [Route("LogicDel")]
        public void LogicDel(Guid id)
        {
            var entity = entityBLL.Details(id);
            entity.IsDelete = true;
            entityBLL.Edit(entity);
        }

        /// <summary>
        /// 客户删除
        /// </summary>
        /// <param name="customerId">客户编号</param>
        [Route("Delete")]
        public void Delete(Guid customerId)
        {
            CustomerOperateRecord operateRecord = new CustomerOperateRecord();
            var entity = entityBLL.Details(customerId);
            operateRecord.BeforeContent = SalesSys.Comm.Utility.SimpleJson.Serializer(entity);
            entity.District = new District();
            entity.District.Children = null;
            entity.District.Parent = null;
            operateRecord.AfterContent = "";
            if (entity == null)
            {
                throw new ApiArgException("未找到用户");
            }
            if (entity.ApprovalState != ApprovalState.Agree)
            {
                using (var tran = new TransactionScope())
                {
                    //删除客户相关联系人
                    austomerContactBLL.DeleteByCustomerId(customerId);
                    customerContactBLL.DeleteByCustomerId(customerId);
                    entityBLL.Delete(customerId);
                    //添加客户操作记录表
                    operateRecord.OperatorAction = "Delete";
                    operateRecord.CustomerId = customerId;
                    operateRecord.OperatorTime = DateTime.Now;
                    operateRecord.OperatorId = ClientHelper.ClientInfo.Id;
                    operateRecord.Id = Guid.NewGuid();
                    customerOperateRecordBLL.Create(operateRecord);
                    tran.Complete();
                }
            }
            else
            {
                throw new ApiArgException("已确认订单不允许删除");

            }
        }

        /// <summary>
        /// 编辑户头
        /// </summary>
        /// <param name="account">户头实体</param>
        [Route("EditAccount")]
        public void PutEditAccount(Account account)
        {
            var old = accountBLL.Details(account.Id);
            var re = old.Customer.Accounts.Any(p => p.Name == account.Name && account.Id != p.Id);
            if (re)
            {
                throw new ApiArgException("重复的账户名称");
            }
            if (old.IsCash)
            {
                old.Remark = account.Remark;
                accountBLL.Edit(old);

            }
            else
            {
                account.Amount = old.Amount;
                account.Receivables = old.Receivables;
                accountBLL.Edit(account);
            }


        }

        /// <summary>
        /// 添加客户户头
        /// </summary>
        /// <param name="customerId">客户编号</param>
        /// <param name="account">户头实体</param>
        [Route("AddAccount")]
        public void PostAddAccount(Guid customerId, Account account)
        {
            var entity = entityBLL.Details(customerId);
            if (entity == null)
            {
                throw new ApiArgException("无法找到的用户");
            }
            var old = entity.Accounts.Any(p => p.Name == account.Name);
            if (old)
            {
                throw new ApiArgException("重复的账户名称");
            }
            account.Amount = 0;
            entity.Accounts.Add(account);
            entityBLL.Edit(entity);
        }
        static IMapper cMapper;
        static IMapper CMapper
        {
            get
            {
                if (cMapper == null)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<Customer, Customer>();
                        cfg.ForAllPropertyMaps(p =>
                            !(typeof(IConvertible).IsAssignableFrom(p.SourceType)) || p.SourceMember.Name == "CreateTime"
                            , (p1, p2) =>
                                p2.Ignore());
                    });
                    cMapper = config.CreateMapper();
                }
                return cMapper;

            }
        }

    }

}
